/*
 * Процесс для печати отчета "Журнал - ордер"
 * Ибраев Е.А.
 *  Создан: 20.08.2012 
 * Изменен: 11.11.2012 
 */

package org.compiere.process;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRXlsExporter;

import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.compiere.model.MAttachment;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import extend.org.compiere.utils.Util;

public class FI_Report_to_Excel extends SvrProcess {
	
	private JasperReport jasperReport = null; // Объект для печати отчета

	private MAttachment attachment; 
	protected ProcessInfo processInfo; 
	private HashMap<String, Object> params = new HashMap<String, Object>();
	
	private static CLogger s_log = CLogger.getCLogger(FI_Report_to_Excel.class);
	
	protected String reportName = null;
	
	
	@Override
	protected void prepare() {

		processInfo = getProcessInfo();
		initParameters();
	}

	@Override
	protected String doIt() throws Exception {
		
		if (reportName == null) {
			s_log.log(Level.INFO, "Report: parameter ReportName is null");
			return null;
		}
		
		if (jasperReport == null)
			if (!initJasperReport(reportName)) {
				s_log.log(Level.INFO, "Report: Don't download report");
				return null;
			};
			
		makeReport(reportName);
		
		return null;
	}
	
	protected boolean makeReport(String reportName) throws JRException {
		
		String xlsName = getXlsName(reportName);
		
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,  params, DB.getConnectionRW());
		JRXlsExporter exporter = new  net.sf.jasperreports.engine.export.JRXlsExporter();
        exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, xlsName);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.exportReport();
        
		try {
			Util.launchFile(new File(xlsName));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
        
        
		return true;
	}
	
	protected String getXlsName(String reportName) throws JRException {
		String Result = null;
		String tmpName = reportName;
		Integer i = 0;
		
		File d = new File(Util.localFilePath);
        String[] lF = d.list(new WildcardFileFilter(tmpName+"*.xls"));
        
        for(int j=0; j < lF.length; j++) {
        	File tmp = new File(lF[j]);
        	tmp.delete();
        }
        
		boolean flag = true;
		while (flag) {
			File f = new File(Util.localFilePath +"/"+ tmpName+".xls");
			try { 
				if (f.exists() && !f.delete()) {
					tmpName = reportName + "(" +(++i).toString() + ")";
				} else {
					flag = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				tmpName = reportName + "(" +(++i).toString() + ")";
			}
		}
		Result = Util.localFilePath +"/"+ tmpName+".xls";
		return Result;
	}
	
	protected boolean initJasperReport(String reportName) {
		try {
			File reportFile = downloadAttachment("attachment: " + reportName + ".jrxml");
			jasperReport = JasperCompileManager.compileReport(reportFile.getAbsolutePath().toString());
		    
        }
		catch (JRException e) {
			s_log.log(Level.SEVERE, "Report: "+reportName, e);
			return false;
		}
		return true;
	}
	
	private File downloadAttachment(String reportPath) {
		File reportFile = null;
		String name = reportPath.substring("attachment:".length()).trim();
		MProcess process = new MProcess(Env.getCtx(), processInfo.getAD_Process_ID(), processInfo.getTransactionName());
		attachment = process.getAttachment();
		if (attachment != null) {
			MAttachmentEntry[] entries = attachment.getEntries();
			MAttachmentEntry entry = null;
			for (int i = 0; i < entries.length; i++) {
				if (entries[i].getName().equals(name)) {
					entry = entries[i];
					break;
				}
			}
			if (entry != null) {
				reportFile = Util.getAttachmentEntryFile(entry);
			}
		}
		return reportFile;
	}


	protected void addParametr(String namePar, Object oPar) {
		params.put(namePar, oPar);
		return;
	}
	
	private void initParameters() {

//		processInfo.setAD_Client_ID(getAD_Client_ID());
		ProcessInfoParameter[] para = getParameter();
		addProcessInfoParameters(params, para);
        addParametr("ad_client_id", getAD_Client_ID());
        
		for (int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;
			else if (name.equals("ReportName")) 
				reportName = (String) para[i].getParameter();
		}
	}
	
    private void addProcessInfoParameters(Map<String, Object> params, ProcessInfoParameter[] para)
    {
    	if (para != null) {
			for (int i = 0; i < para.length; i++) {
				if (para[i].getParameter_To() == null) {
					params.put(para[i].getParameterName(), para[i].getParameter());
				} else {
	                params.put( para[i].getParameterName()+"1", para[i].getParameter());
	                params.put( para[i].getParameterName()+"2", para[i].getParameter_To());
				}
			}
    	}
	}
    
}
